import { defineStore } from "pinia";
import {
  getCurrencyRate,
  login,
  getUserInfo,
  faceBookLogin,
} from "@/api/common";
import { getCategory } from "@/api/product";
import { setToken, clearAccessTokens } from "@/utils/request";
import { Session, Local } from "@/utils/storage";

export const useUser = defineStore("user", {
  state: () => ({
    user: {},
    currencyRate: undefined,
    category: [],
    settlementGoods: [],
    compareGoods: [],
    facebookInfo: {},
  }),
  actions: {
    async getCurrencyRateHandle() {
      const { data } = await getCurrencyRate();
      this.currencyRate = data.data;
    },
    async loginHandler(formData) {
      const { data } = await login(formData);
      setToken(data.data.accessToken);
      await this.getUserInfo(true);
    },
    async facebookLoginHandler(formData) {
      this.facebookInfo = formData;
      Local.set("facebookInfo", formData);
      const { data } = await faceBookLogin(formData);
      setToken(data.data.accessToken);
      await this.getUserInfo(true);
    },
    async getUserInfo(forcedUpdate) {
      // 存储用户信息到浏览器缓存
      if (!forcedUpdate && Session.get("user")) {
        this.user = Session.get("user");
      } else {
        const { data } = await getUserInfo();
        this.user = data.data;
        Session.set("user", this.user);
      }
      this.facebookInfo = Local.get("facebookInfo");
    },
    async getCategory() {
      const cacheCategory = Session.get("category");
      if (!cacheCategory) {
        const { data } = await getCategory();
        this.category = data.data;
        // navData.value = category.data;
        Session.set("category", this.category);
      } else {
        this.category = cacheCategory;
      }
    },
    async logout() {
      // await logout()
      // // debugger
      this.user = {};
      clearAccessTokens();
      location.href = "/";
    },
    setSettlementGoods(goodsList) {
      this.settlementGoods = goodsList;
    },
  },
});
